<template>
  <el-form
    class="loginForm"
    ref="loginFormRef"
    :model="loginForm"
    :rules="loginRules"
    size="large"
  >
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        placeholder="密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <!-- <el-button :icon="CircleClose" size="large" @click="resetForm(loginFormRef)"> 重置 </el-button> -->
    <el-button
      :icon="UserFilled"
      type="primary"
      size="large"
      :loading="loading"
      @click="login(loginFormRef)"
    >
      登录
    </el-button>
  </div>

  <!-- <div class="others">
    <el-button @click="setLoginState(LoginStateEnum.MOBILE)"> 手机登录 </el-button>
    <el-button @click="setLoginState(LoginStateEnum.QR_CODE)"> 二维码登录 </el-button>
    <el-button @click="setLoginState(LoginStateEnum.REGISTER)"> 注册 </el-button>
  </div> -->
  <!-- 
  <div class="divide">
    <el-divider> 其他登录方式 </el-divider>
  </div> -->

  <!-- <div class="otherloginWay">
    <div class="oneway">
      <img src="../../../assets/images/qq.svg" alt="" />
    </div>
  </div> -->
</template>

<script setup lang="ts">
import { ref, reactive, unref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElMessage, ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
// import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
// import { useMenuStore } from "@/stores/modules/menu";
// import { LoginStateEnum, } from "./useLogin";
// import { computed } from "vue";
import { getTimeState } from "@/utils";
import { initDynamicRouter } from "@/router/modules/dynamicRouter";
// const { setLoginState, getLoginState } = useLoginState();
// const authStore = useMenuStore();
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

// const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "sq",
  password: "987654",
  // username: "13002003166",
  // password: "123456"
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const res: any = await loginApi({
        ...loginForm,
        password: md5(loginForm.password),
      });
      // userStore.setToken(data.access_token);
      console.log("登录", res);
      if (res.code == 200) {
        userStore.setToken(res.data.token);

        // userStore.setToken(res.data.token);
        // userStore.setUserInfo({ username: loginForm.username });
        // await authStore.getAuthMenuList();
        //跳转到加粉页
        // router.push({
        //   path: "/upload"
        // });
        // 2.添加动态路由
        userStore.setUserInfo(res.data);
        // await authStore.getAuthMenuList();
        // await initDynamicRouter();

        // 2.添加动态路由
        await initDynamicRouter();

        // 3.清空 tabs、keepAlive 数据
        tabsStore.setTabs([]);
        keepAliveStore.setKeepAliveName([]);

        // 4.跳转到首页
        router.push(HOME_URL);
        // router.push({
        //   path: "/addriends"
        // });

        ElNotification({
          title: getTimeState(),
          message: "欢迎登录",
          type: "success",
          duration: 3000,
        });

        console.log("1", res.data);
        localStorage.setItem("userInfo", JSON.stringify(res.data));

        localStorage.setItem("token", res.data.token);
      } else {
        console.log("dcuowu ");
        ElMessage({
          message: "用户不存在或账号密码错误",
          type: "warning",
        });
      }

      // 2.添加动态路由
      // await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      // tabsStore.setTabs([]);
      // keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      // router.push(HOME_URL);
      // ElNotification({
      //   title: getTimeState(),
      //   message: "欢迎登录 Geeker-Admin",
      //   type: "success",
      //   duration: 3000
      // });
    } catch (e: any) {
      console.log("e", e);

      if (e.status == 500) {
        ElMessage({
          message: "服务器异常，请联系管理员",
          type: "error",
        });
      } else {
        ElMessage({
          message: "用户不存在或账号密码错误",
          type: "warning",
        });
      }
    } finally {
      loading.value = false;

      console.log("4555");
    }
  });
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@use "../index.scss";
</style>
